package com.cyl.XmlDemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import com.cyl.XmlDemo.entity.Room;
import com.cyl.XmlDemo.entity.RoomList;
import com.cyl.XmlDemo.entity.StompClient;
import com.cyl.XmlDemo.entity.UserList;
import com.cyl.XmlDemo.interceptor.HttpHandshakeInterceptor;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig extends AbstractWebSocketMessageBrokerConfigurer {


	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableSimpleBroker("/queue","/topic");
		registry.setApplicationDestinationPrefixes("/app");
	}
	
/*	@Override
	public void configureClientInboundChannel(ChannelRegistration registration) {
		registration.setInterceptors(new ChannelInterceptorAdapter(){
			@Override
			public Message<?> preSend(Message<?> message, MessageChannel channel) {
				StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message,StompHeaderAccessor.class);
				if(StompCommand.CONNECT.equals(accessor.getCommand())){
					Principal user;
					accessor.setUser(user);
				}
				return message;
			}
		});
	}*/

	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/marcopolo").setHandshakeHandler(handShakeHandler()).setAllowedOrigins("*").addInterceptors(handshakeInterceptor()).withSockJS();
	}
	
	
	@Bean
	public HandshakeInterceptor handshakeInterceptor(){
		return new HttpHandshakeInterceptor();
	}
	
	@Bean 
	public DefaultHandshakeHandler handShakeHandler(){
		return new MyHandshakeHandler();
	}
	
	@Bean
	public StompClient userListInstance(){
		return StompClient.getInstance();
	}
	
	@Bean
	public Room roomInstance(){
		return Room.getInstance();
	}
	
	@Bean
	public RoomList roomListInstance(){
		return RoomList.getInstance();
	}
	
	@Bean
	public UserList clientInstance(){
		return UserList.getInstance();
	}
}
